package com.alibaba.moco.util;

import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.util.*;

/**
 * 滴滴签名算法实现
 * Created by wb-lj240895 on 2016/11/4.
 */
public class DidiSignUtil {

    /**
     * 生成签名的时候,将颁发的sign_key加入到传递的参数中，参与加密
     * 传递的参数(包含sign_key)按照key从小到大排序,然后，已&形式连接，生成小写的md5串
     * 生成sign后，sign和其他参数一起参加传递，对于中文在传递的过程中，需要进行urlencode，加密的时候不进行urlencode
     * sign_key不要参与传递
     * @param request
     * @return
     */
    public static String sign(HttpServletRequest request){
        Map<String,String[]> params = request.getParameterMap();
        //排序
        Map<String,String[]> treeParams = new TreeMap<String,String[]>(params);
        //拼接
        StringBuilder paramBuilder = new StringBuilder();
        for (String[] value : treeParams.values()){
            if (value != null && value.length>0 && !StringUtils.isBlank(value[0])){
                String val = value[0];
                paramBuilder.append(val).append("&");
            }
        }
        if (paramBuilder.length()>0) {
            paramBuilder.deleteCharAt(paramBuilder.length()-1);
            //生成Md5值
            String digestStr = MD5(paramBuilder.toString());
            return digestStr;
        }
        return null;
    }

    public static String MD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];

        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }
}
